package com.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.gulimall.product.dao.CategoryBrandRelationDao;
import com.gulimall.product.service.CategoryBrandRelationService;
import com.gulimall.product.vo.Catalog2VO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.common.utils.PageUtils;
import com.common.utils.Query;

import com.gulimall.product.dao.CategoryDao;
import com.gulimall.product.entity.CategoryEntity;
import com.gulimall.product.service.CategoryService;

@Slf4j
@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    final CategoryDao categoryDao;

    @Autowired
    private CategoryBrandRelationDao categoryBrandRelationService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private RedissonClient redisson;

    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService1;

    public CategoryServiceImpl(CategoryDao categoryDao) {
        this.categoryDao = categoryDao;
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(new Query<CategoryEntity>().getPage(params), new QueryWrapper<CategoryEntity>());

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {

        // 1.查出所有分类
        List<CategoryEntity> entities = categoryDao.selectList(null);
        // 2.组装成父子分类

        // 2.1 找到所有的一级分类
        List<CategoryEntity> level1Menus = entities.stream().filter(categoryEntity -> categoryEntity.getParentCid() == 0).map((menu) -> {
            menu.setChildren(getChildren(menu, entities));
            return menu;
        }).sorted((menu1, menu2) -> {
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());

        return level1Menus;
    }

    @Override
    public void removeMenuByIds(List<Long> list) {

        // todo:检车当前菜单是否被其他地方引用批量删除
        categoryDao.deleteBatchIds(list);
    }

    /**
     * 根据当前节点,查询出所有父节点
     *
     * @param catelogId 当前节点id
     * @return 父节点id 数组
     */
    @Override
    public Long[] findCatelogPath(Long catelogId) {

        List<Long> paths = new ArrayList<>();

        List<Long> parentsPath = findParentPath(catelogId, paths);
        Collections.reverse(parentsPath);

        return paths.toArray(new Long[parentsPath.size()]);
    }

    // 递归查找所有菜单的子菜单
    private List<CategoryEntity> getChildren(CategoryEntity root, List<CategoryEntity> all) {

        List<CategoryEntity> children = all.stream().filter((menu) -> {
            // 找到子菜单
            return Objects.equals(menu.getParentCid(), root.getCatId());
        }).map(menu -> {
            // 子菜单也需要找到对应的子菜单
            menu.setChildren(getChildren(menu, all));
            return menu;
        }).sorted((menu1, menu2) -> {
            // 菜单排序
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());

        return children;
    }

    // 递归查找所有父节点路径
    public List<Long> findParentPath(Long catelogId, List<Long> path) {
        // 1. 添加当前节点 ID
        path.add(catelogId);

        // 2. 查询当前节点
        CategoryEntity category = this.getById(catelogId);
        if (category == null) {
            throw new RuntimeException("未找到对应的分类");
        }

        // 3. 递归查找父节点
        if (category.getParentCid() != 0) {
            findParentPath(category.getParentCid(), path);
        }

        return path;
    }

    @CacheEvict(value = "category", key = "#root.methodName", allEntries = true)
    @Override
    public void updateCascade(CategoryEntity category) {

        this.updateById(category);

        categoryBrandRelationService1.updateCategory(category);

    }

    @Cacheable(value = "category", key = "#root.methodName")
    @Override
    public List<CategoryEntity> getLevelCategory() {

        List<CategoryEntity> categoryEntities = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));

        return categoryEntities;
    }


    /**
     * 缓存分类菜单
     */
    @Override
    public Map<String, List<Catalog2VO>> getCatalogJson() {

        /**
         * 空结果缓存：解决缓存穿透
         * 设置过期时间(加随机值)：缓存雪崩
         * 加锁：解决缓存击穿
         */

        // 查询缓存
        String catalogJson = redisTemplate.opsForValue().get("catalogJson");
        // 缓存没有,查询数据库放入缓存
        if (StringUtils.isEmpty(catalogJson)) {

            Map<String, List<Catalog2VO>> catalogJsonFromDB = getCatalogJsonWithRedissonLOCK();
            return catalogJsonFromDB;
        }

        Map<String, List<Catalog2VO>> result = JSON.parseObject(catalogJson, new TypeReference<Map<String, List<Catalog2VO>>>() {
        });
        System.out.println("缓存中存在直接返回 线程id=" + Thread.currentThread().getId());
        return result;
    }

    public Map<String, List<Catalog2VO>> getCatalogJsonWithRedissonLOCK() {

        // 1.占分布式锁
        ValueOperations<String, String> ops = redisTemplate.opsForValue();
        String catalogJson = ops.get("catalogJson");
        if (!StringUtils.isEmpty(catalogJson)) {
            // 返回缓存中的数据
            Map<String, List<Catalog2VO>> chacheData = JSON.parseObject(catalogJson, new TypeReference<Map<String, List<Catalog2VO>>>() {
            });
            return chacheData;
        } else {
            // 缓存未命中
            RLock lock = redisson.getLock("lock");
            try {
                // 2.1 获取锁（默认看门狗机制，锁自动续期）
                lock.lock();

                // 2.2 双重检查（防止在等待锁期间其他线程已写入缓存）
                catalogJson = ops.get("catalogJson");
                if (!StringUtils.isEmpty(catalogJson)) {
                    return JSON.parseObject(catalogJson, new TypeReference<Map<String, List<Catalog2VO>>>() {
                    });
                }

                // 3. 查询数据库
                Map<String, List<Catalog2VO>> dbData = getCatalogJsonFromDB();

                // 4. 将结果写入缓存
                String jsonString = JSON.toJSONString(dbData);
                ops.set("catalogJson", jsonString); // 设置缓存过期时间（1小时）

                return dbData;
            } finally {
                // 5. 释放锁
                if (lock.isLocked() && lock.isHeldByCurrentThread()) {
                    lock.unlock();
                }
            }
        }
    }


    /**
     * 利用Redis作为分布式锁
     */
    public Map<String, List<Catalog2VO>> getCatalogJsonWithRedisLOCK() {

        // 1.占分布式锁
        ValueOperations<String, String> ops = redisTemplate.opsForValue();
        String uuid = UUID.randomUUID().toString();
        // 设置过期时间和加锁必须是原子操作(同步进行的)
        Boolean lock = ops.setIfAbsent("lock", uuid, 300, TimeUnit.SECONDS);

        // 说明加锁成功
        if (lock) {
            System.out.println("获取锁成功 线程id=" + Thread.currentThread().getId());
            String catalogJson = ops.get("catalogJson");
            // 缓存为空,查询数据库
            if (StringUtils.isEmpty(catalogJson)) {
                Map<String, List<Catalog2VO>> catalogJsonFromDB;
                try {
                    // 查询数据库
                    System.out.println("查询数据库设置到缓存 线程id=" + Thread.currentThread().getId());
                    catalogJsonFromDB = getCatalogJsonFromDB();
                    // 放入缓存
                    catalogJson = JSON.toJSONString(catalogJsonFromDB);
                    ops.set("catalogJson", catalogJson);

                } finally {
                    // 获取值+对比成功删除=原子操作
                    String luaScript = "if redis.call('get',KEYS[1]) == ARGV[1]\n" +
                            "then\n" +
                            "    return redis.call('del',KEYS[1])\n" +
                            "else\n" +
                            "    return 0\n" +
                            "end";
                    redisTemplate.execute(
                            new DefaultRedisScript<Long>(luaScript, Long.class),
                            Arrays.asList("lock"),
                            uuid);
                    System.out.println("删锁成功 线程id=" + Thread.currentThread().getId());
                }
                return catalogJsonFromDB;
            } else {
                // 缓存不为空
                System.out.println("缓存不为空,返回redis中数据 线程id=" + Thread.currentThread().getId());
                return JSON.parseObject(catalogJson, new TypeReference<Map<String, List<Catalog2VO>>>() {
                });
            }

        } else {
            // 获取分布式锁失败,查看缓存中是否有数据
            String catalogJson = ops.get("catalogJson");
            if (StringUtils.isEmpty(catalogJson)) {
                // 没有数据
                System.out.println("获取锁失败,缓存中也不存在,自旋重试...... 线程Id=" + Thread.currentThread().getId());

                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                return getCatalogJsonWithRedisLOCK();
            } else {
                // 有数据
                System.out.println("获取锁失败,缓存中存在,返回缓存中数据线程Id=" + Thread.currentThread().getId());
                return JSON.parseObject(catalogJson, new TypeReference<Map<String, List<Catalog2VO>>>() {
                });
            }
        }
    }


    /**
     * 本地锁
     * 问题:在分布式情况下,只能锁住自己本服务器中的锁,锁不住其他服务器
     */
    public synchronized Map<String, List<Catalog2VO>> getCatalogJsonWithLocalLOCK() {

        synchronized (this) {

            // 拿到锁,先查看缓存中是否存在数据
            ValueOperations<String, String> ops = redisTemplate.opsForValue();
            String catalogJson = ops.get("catalogJson");

            // 存在,说明之前有人进来拿到锁,并放入到缓存中
            if (!StringUtils.isEmpty(catalogJson)) {
                Map<String, List<Catalog2VO>> result = JSON.parseObject(catalogJson, new TypeReference<Map<String, List<Catalog2VO>>>() {
                });
                log.info("============缓存命中========");
                return result;
            } else {

                // 不存在,说明第一次进来,需要到数据库查询,并放入到缓存中
                log.info("============查询了数据库========");
                Map<String, List<Catalog2VO>> catalogJsonFromDB = getCatalogJsonFromDB();

                // 查询到的数据放入到缓存中
                ops.set("catalogJson", JSON.toJSONString(catalogJsonFromDB));

                return catalogJsonFromDB;
            }
        }
    }


    /**
     * 从数据库查询分类菜单
     */
    public Map<String, List<Catalog2VO>> getCatalogJsonFromDB() {

        // 1.查询所有分类，按照parentCid分组
        Map<Long, List<CategoryEntity>> categoryMap = baseMapper.selectList(null).stream().collect(Collectors.groupingBy(CategoryEntity::getParentCid));

        // 2.获取1级分类（parentCid为0的分类）
        List<CategoryEntity> level1Categorys = Optional.ofNullable(categoryMap.get(0L)).orElse(Collections.emptyList());

        // 3.封装数据
        Map<String, List<Catalog2VO>> result = level1Categorys.stream().collect(Collectors.toMap(l1Category -> l1Category.getCatId().toString(), l1Category -> {
            // 4.获取2级分类
            List<CategoryEntity> level2Categorys = Optional.ofNullable(categoryMap.get(l1Category.getCatId())).orElse(Collections.emptyList());

            // 5.封装2级分类VO
            return level2Categorys.stream().map(l2Category -> {
                // 6.获取3级分类
                List<Catalog2VO.Catalog3Vo> catalog3Vos = Optional.ofNullable(categoryMap.get(l2Category.getCatId())).orElse(Collections.emptyList()).stream().map(l3Category -> new Catalog2VO.Catalog3Vo(l2Category.getCatId().toString(), l3Category.getCatId().toString(), l3Category.getName())).collect(Collectors.toList());

                // 7.封装2级分类VO
                return new Catalog2VO(l1Category.getCatId().toString(), catalog3Vos, l2Category.getCatId().toString(), l2Category.getName());
            }).collect(Collectors.toList());
        }));

        return result;
    }
}